import { to } from "await-to-js";
import defaultAvatar from "@/assets/images/avatar.jpg";
import store from "@/store";
import { getToken, removeToken, setToken } from "@/utils/auth";
import {
  LoginData,
  SmsLoginData,
  SysIdentityVo,
} from "@/service/api/loginTypes";
import {
  login as loginApi,
  smsLogin as smsLoginApi,
  logout as logoutApi,
  getUserInfo as getUserInfoApi,
} from "@/service/api/login";

export const useUserStore = defineStore("user", () => {
  const token = ref(getToken());
  const name = ref("");
  const nickName = ref("");
  const userId = ref<string>("");
  // 用户身份列表
  const identityList = ref<SysIdentityVo[]>([]);
  // 是否为超级管理员
  const isSuperAdmin = ref(false);
  const avatar = ref("");
  // 用户角色编码集合 → 判断路由权限
  const roleKeys = ref<Array<string>>([]);
  // 用户权限编码集合 → 判断按钮权限
  const permissionCodes = ref<Array<string>>([]);

  /**
   * 登录
   *
   * @param userInfo 用户登录表单数据
   *
   * @returns 数据请求的Promise
   */
  const login = async (userInfo: LoginData): Promise<boolean> => {
    console.log(userInfo);

    const [err, res] = await to(loginApi(userInfo));
    if (!err) {
      const { data } = res;
      if (data != null) {
        setToken(data.token);
        token.value = data.token;
        return true;
      }
    }
    return false;
  };

  /**
   * 短信登录
   * @param userInfo
   */
  const smsLogin = async (userInfo: SmsLoginData): Promise<boolean> => {
    console.log(userInfo);

    const [err, res] = await to(smsLoginApi(userInfo));
    if (!err) {
      const { data } = res;
      if (data != null) {
        setToken(data.token);
        token.value = data.token;
        return true;
      }
    }
    return false;
  };

  // 获取用户信息
  const getUserInfo = async (): Promise<void> => {
    const [err, res] = await to(getUserInfoApi());
    if (!err) {
      const { data } = res;

      if (data != null) {
        const user = data.user;
        const profile =
          user?.avatar == "" || user?.avatar == null
            ? defaultAvatar
            : user.avatar;

        // 验证返回的roles是否是一个非空数组
        if (data.roleKeys && data.roleKeys.length > 0) {
          roleKeys.value = data.roleKeys;
          permissionCodes.value = data.permissionCodes ?? [];
        } else {
          roleKeys.value = ["ROLE_DEFAULT"];
        }

        // 验证返回的identityList是否为空数组
        identityList.value = user?.identityList ?? [];

        name.value = user?.userName ?? "未命名";
        nickName.value = user?.nickName ?? "未命名";
        avatar.value = profile;
        userId.value = user?.id ?? "";
        isSuperAdmin.value = user?.superAdmin ?? false;
        return Promise.resolve();
      }
    }

    return Promise.reject(err);
  };

  // 注销
  const logout = async (): Promise<void> => {
    await logoutApi();

    token.value = "";
    roleKeys.value = [];
    permissionCodes.value = [];
    removeToken();
  };

  return {
    userId,
    token,
    nickName,
    avatar,
    roleKeys,
    permissionCodes,
    identityList,
    isSuperAdmin,
    login,
    smsLogin,
    getUserInfo,
    logout,
  };
});

export default useUserStore;

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
